﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace XYZShell.CSHelper.Web.WCF
{
    public static class ServiceProxyFactory
    {
        private static ConcurrentDictionary<string, object> wcfServices = new ConcurrentDictionary<string, object>();
        /// <summary>
        /// 根据配置创建远程WCF服务调用接口
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="endpointName"></param>
        /// <returns></returns>
        public static T Create<T>(string endpointName)
        {
            if (string.IsNullOrEmpty(endpointName))
            {
                throw new ArgumentNullException("endpointName");
            }
            object wcfClient = null;
            if (wcfServices.TryGetValue(endpointName,out wcfClient))
            {
                if (wcfClient!=null && wcfClient is T)
                {
                    return (T)wcfClient;
                }
            }
            var wcfc = (T)((object)new ServiceRealProxy<T>(endpointName).GetTransparentProxy());
            wcfServices.TryAdd(endpointName, wcfc);
            return wcfc;
        }
    }
}
